package com.example.android.extensions

import android.app.Activity
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.core.view.children
import com.example.android.MyApplication
import com.example.android.R
import com.example.android.ServicesObject
import com.example.android.utils.MyDialog
import com.google.android.material.snackbar.Snackbar
import com.tapadoo.alerter.Alert
import com.tapadoo.alerter.Alerter

val Activity.Services: ServicesObject
    get() = (application as MyApplication).ServicesObject

fun Activity.SetOnServicesConnected(onServicesConnected: () -> Unit) {
    (application as MyApplication).SetOnServicesConnected(onServicesConnected)
}

fun Activity.Alert(message: String,
                   duration: Int = Snackbar.LENGTH_SHORT, setAlerter: (alerter: Snackbar) -> Unit = { }) {
    val alertBar = findViewById<RelativeLayout>(R.id.main_alert_bar)
    val snackBar = Snackbar.make(alertBar, message, duration)
        .setAnimationMode(Snackbar.ANIMATION_MODE_SLIDE)
    setAlerter(snackBar)
    snackBar.show()
}

fun Activity.AlertBar(setAlerter: (alerter: Alerter) -> Unit) {
    // default settings
    val alerter = Alerter.create(this)
        .setBackgroundColor(R.color.crane_purple_900)
        .setDuration(1000)

    setAlerter(alerter)
    alerter.show()
    // 解决issue, 让消息框悬浮
    // https://github.com/Tapadoo/Alerter/issues/283
    val children = (window.decorView as ViewGroup).children
    children.forEach {
        if(it.javaClass == Alert::class.java) {
            (it as Alert).translationZ = 100f
        }
    }
}

fun Activity.AlertDialog(setDialog: (dialog: MyDialog) -> Unit) {
    val dialog = MyDialog(this)
    dialog.create()
    setDialog(dialog)
    dialog.show()
}